<?php
    $cntFio = Arr::getValue($params, 'byFio', array());
    $cntId = json_encode(Arr::getValue($params, 'byId', array()));
    $tableHtml = '';

    foreach ($cntFio as $cnt) {
        $gender = $cnt['gender']? 'M' : 'Ж';
        $ava    = $cnt['photo']? $cnt['photo'] : APP_HTML_AVA_PATH.'0.png';
        if ($cnt['rating']>0) $cnt['rating'] = '+'.$cnt['rating'];
$tableHtml .= <<<__HTML__
        <tr id="cnt_item_{$cnt['id']}">
            <td><img src="{$ava}" height="35" alt="img" border="0"></td>
            <td forfield="fio">{$cnt['fio']}</td>
            <td forfield="job">{$cnt['job']}</td>
            <!--td>{$gender}</td>
            <td>{$cnt['phone']}</td>
            <td>{$cnt['mail']}</td-->
            <td forfield="rating" width="50">{$cnt['rating']}</td>
        </tr>
__HTML__;
    }
?>

<?php
$e = Arr::getValue($params, 'error', false);

if ($e) {?>
<div class="alert alert-danger"> <?php echo $e; ?> </div>
<?php } ?>

<table class="table table-striped table-bordered table-condensed" id="cntListTable">
    <thead>
        <tr>
            <th width="35">&nbsp;</th>
            <th>ФИО</th>
            <th>Должность</th>
            <!--th>Пол</th>
            <th>Телефон</th>
            <th>Почта</th-->
            <th>Рейтинг</th>
        </tr>
    </thead>
    <tbody>
        <?php echo $tableHtml;?>
    </tbody>
</table>



<div id="cntInfo-tmpl" class="hidden">
    <div id="cntInfo-{%id%}" class="well " style="display:none;">
        <div class="pull-right" style=" min-width:60%; max-width:60%">
            <h4>{%lastname%}</h4>
            <h4>{%firstname%}</h4>
            <h4>{%middlename%}</h4>
            <hr style="margin:3px !important;">
            <p><strong>Должность:</strong> {%job%}</p>
            <p><strong>Пол:</strong> {%genderVisible%}</p>
        </div>
        <img id="cntAva-{%id%}" src="<?php echo APP_HTML_DEF_AVA; ?>" alt="img" border="0" style="max-width:80px; margin: 0 5px 5px 0;">
        <div class="clear_both"></div>

        <table class="table table-striped table-bordered "  style="margin-top: 5px;">
            <tbody>
                <tr><td><strong>Тел:</strong></td><td>{%phone%}</td></tr>
                <tr><td><strong>Email:</strong></td><td>{%mail%}</td></tr>
                <tr><td><strong>Другие контакты:</strong></td><td>{%im%}</td></tr>
            </tbody>
        </table>

        <div class="pull-right noWrap" id="ratingCtrls-{%id%}" style="margin-bottom: 5px;">
            <span style="margin-right:20px;"><strong>Рейтинг:</strong></span>
            <button type="button" class="btn" id="cntRatingBtn-{%id%}-minus"><i class="icon-minus"></i></button>
            <input id="cntRatingVal-{%id%}" type="text" readonly="readonly" value="+5" style="width:20px; margin:0;cursor:default;">
            <button type="button" class="btn" id="cntRatingBtn-{%id%}-plus"><i class="icon-plus"></i></button>
        </div>
        <div class="clear_both"></div>

        <div class="form-actions">
            <button type="button" class="btn btn-info" id="cntInfo-{%id%}-edit"><i class="icon-edit icon-white"></i> Изменить</button>
            <button type="button" class="btn btn-danger pull-right" id="cntInfo-{%id%}-cancel"><i class="icon-remove icon-white"></i> Закрыть</button>
        </div>
    </div>
</div>



<script>
var contactsData = <?php echo $cntId; ?>;
var DEF_AVA = '<?php echo APP_HTML_DEF_AVA; ?>';

function cntDetails(elm) {
    var id = elm.id.replace('cnt_item_', '');

    var item = (contactsData.hasOwnProperty(id) && contactsData[id])? contactsData[id] : {};
    item.photo = item.photo || DEF_AVA;
    item.gender = item.gender || -1;
    item.genderVisible = formatGenderToInt(item.gender)*1;
    if(item.genderVisible > -1) item.genderVisible = (item.genderVisible>0)? 'Мужской' : 'Женский';
    else item.genderVisible = '??';
    item.gender = formatGenderToChar(item.gender);

    item.rating = item.rating || 0;


    var value;

    var detailsContent = $('#cntInfo-tmpl').html();

    for (var prop in item) {
        if (!item.hasOwnProperty(prop)) continue;
        value = item[prop]?  item[prop] : '';
        detailsContent = detailsContent.gReplace('{%'+prop+'%}', value);
    }

    ovlAlert(detailsContent, "&nbsp;");
    $('#cntInfo-'+item.id).css({display:'block'});

    var btnreset    = $('#cntInfo-'+item.id+'-cancel').click(function() {ovlClose();});
    var btnedit    = $('#cntInfo-'+item.id+'-edit').click(function() {openEditContactForm(item.id);});

    var ratingInc   = $('#cntRatingBtn-'+id+'-plus');
    var ratingDec   = $('#cntRatingBtn-'+id+'-minus');
    var ratingFld   = $('#cntRatingVal-'+id);
    var avaImg      = $('#cntAva-'+id);

    ratingFld.val(formatRating(item.rating));
    avaImg.attr({src:item.photo});
    checkRatingCtrls(id);

    ratingInc.click(function() {
        updateRating(id, '<?php echo ACTIONS::CONTACT_RATING_INC; ?>');
    });
    ratingDec.click(function() {
        updateRating(id, '<?php echo ACTIONS::CONTACT_RATING_DEC; ?>');
    });
}


function updateRating(id, action) {
    var ratingInc   = $('#cntRatingBtn-'+id+'-plus');
    var ratingDec   = $('#cntRatingBtn-'+id+'-minus');
    var ratingFld   = $('#cntRatingVal-'+id);

    disableRatingCtrls(id);

    var send = {
        action: action,
        id: id
    }

    jsonRequest(
        'contacts.php',
        send,

        function(data) {
            if(!checkSession(data)) {
                enableRatingCtrls(id);
                Elm.loginFormModal.dialog('open');
                return;
            }
            if (!data.state) {
                enableRatingCtrls(id);
                ratingFld.addClass('error');
                setTimeout(function(){ratingFld.removeClass('error');}, 2000);
                return;
            }

            if (data.hasOwnProperty('relocate') && data.relocate) window.location.assign(data.relocate);
            else {
                if (data.hasOwnProperty('response_data') && data.response_data.hasOwnProperty('new_rating')) {
                    ratingFld.val(formatRating(data.response_data.new_rating));
                    contactsData[id].rating = data.response_data.new_rating;
                    updateCntListString({
                        id: id,
                        rating: formatRating(data.response_data.new_rating)
                    });
                    //$('#cnt_item_'+id).find('td.tdRating').html(formatRating(data.response_data.new_rating));
                    //enableRatingCtrls(id);
                    ratingFld.addClass('success');
                    setTimeout(function(){ratingFld.removeClass('success');}, 2000);
                }
                else {
                    enableRatingCtrls(id);
                    ratingFld.addClass('error');
                    setTimeout(function(){ratingFld.removeClass('error');}, 2000);
                }

            }
        },

        function() {
            enableRatingCtrls(id);
            ratingFld.addClass('error');
            setTimeout(function(){ratingFld.removeClass('error');}, 2000);
        }
    );
}





function disableRatingCtrls(id) {
    $('#ratingCtrls-'+id).find('button, input').attr({disabled:'disabled'});
}

function enableRatingCtrls(id) {
    $('#ratingCtrls-'+id).find('button, input').removeAttr('disabled');
    checkRatingCtrls(id);
}

function checkRatingCtrls(id) {
    var ratingInc = $('#cntRatingBtn-'+id+'-plus');
    var ratingDec = $('#cntRatingBtn-'+id+'-minus');
    var ratingFld = $('#cntRatingVal-'+id);

    var r = ratingFld.val().gReplace('+', '');

    if (r*1 <= -5) ratingDec.attr({disabled:'disabled'});
    else ratingDec.removeAttr('disabled');

    if (r*1 >= 5) ratingInc.attr({disabled:'disabled'});
    else ratingInc.removeAttr('disabled');
}



function openEditContactForm(id) {
    var item = (contactsData.hasOwnProperty(id) && contactsData[id])? contactsData[id] : false;
    if (!item) return false;

    item.gender = item.gender || -1;
    item.gender = formatGenderToChar(item.gender);


    editContact(item, function(data) {
        var newItem = data.request_data;
        newItem.fio = newItem.lastname+' '+newItem.firstname+' '+newItem.middlename;
        //console.log(newItem);
        delete(newItem.action);
        $.extend(contactsData[id], newItem);
        cntDetails($('#cnt_item_'+id).get(0));
        updateCntListString(newItem);
        //reloadCntList(Elm.cntListTable.parent());
    });
}

function updateCntListString(cdata) {
    cdata = cdata || false;

    if (!cdata.hasOwnProperty('id')) return;
    var id = cdata.id;
    //cdata.fio = cdata.lastname+' '+cdata.firstname+' '

    $('#cnt_item_'+id+' td').each(function(){
        var td = $(this);
        var f = td.attr('forfield');
        if (f && cdata.hasOwnProperty(f)) td.html(cdata[f]);
    });

}







$(function() {
    Elm.cntListTable = $('#cntListTable');

    $('#cntListTable tbody tr').click(function() {
        cntDetails(this);
    });
});
</script>